<?php

namespace Tests\Feature;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Livewire\CampaignManager\EditEntity;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformEntity;
use App\Models\User;
use App\Services\LinkedIn\LinkedIn;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Livewire\Livewire;
use Mockery;
use Tests\TestCase;

/**
 * Duplicating and deleting from the campaign manager.
 *
 * A copy is always made paused. A delete shows what the object has delivered,
 * is never sent without being acknowledged, and is not sent at all if the
 * object delivered more after it was proposed.
 */
class CampaignManagerStructureEditTest extends TestCase
{
    use RefreshDatabase;

    private const CAMPAIGN_ID = '120252047635070626';

    private const COPY_ID = '120252047635079999';

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

    private bool $adSetCopyFails = false;

    private User $user;

    /** @var array{campaign: array<string, mixed>, adsets: list<array<string, mixed>>, ads: list<array<string, mixed>>} */
    private array $meta = ['campaign' => [], 'adsets' => [], 'ads' => []];

    /** @var array{spend: string, impressions: string} */
    private array $delivered = ['spend' => '0', 'impressions' => '0'];

    /** @var list<array{id: string, fields: array<string, mixed>}> */
    private array $copies = [];

    /** @var list<string> */
    private array $deleted = [];

    private bool $adCopyFails = false;

    private bool $eventCopyMismatch = false;

    private bool $cleanupRefused = false;

    private bool $originalChangesDuringCopy = false;

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*', 'google:*', 'linkedin:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 50,
            'campaign-manager.edit_platforms' => ['meta', 'google', 'linkedin'],
            'campaign-manager.edit_categories' => ['name', 'status', 'duplicate', 'delete'],
        ]);

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

        $this->meta['campaign'] = [
            'id' => self::CAMPAIGN_ID, 'name' => 'Winter Sale', 'status' => 'PAUSED',
            'effective_status' => 'PAUSED', 'objective' => 'OUTCOME_SALES', 'account_id' => '111',
        ];
        $this->meta['adsets'] = [['id' => '2001', 'name' => 'US mobile', 'status' => 'ACTIVE', 'campaign_id' => self::CAMPAIGN_ID]];
        $this->meta['ads'] = [['id' => '3001', 'name' => 'Video A', 'status' => 'ACTIVE', 'adset_id' => '2001']];

        Http::fake(function (Request $request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if ($request->method() === 'DELETE') {
                if ($this->cleanupRefused && basename($path) === '2002') {
                    return Http::response(['success' => false]);
                }

                return Http::response(['success' => $this->remove(basename($path))]);
            }

            if ($request->method() === 'POST' && str_ends_with($path, '/copies')) {
                if ($this->adCopyFails && basename(dirname($path)) === '3001') {
                    return Http::response(['error' => ['message' => 'Ad copy refused', 'code' => 100]], 400);
                }

                return Http::response($this->copy(basename(dirname($path)), array_diff_key($request->data(), ['access_token' => true])));
            }

            if ($request->method() === 'POST' && str_ends_with($path, '/adsets')) {
                $fields = array_diff_key($request->data(), ['access_token' => true]);
                $stored = array_map(fn (mixed $value): mixed => is_string($value) && (str_starts_with($value, '{') || str_starts_with($value, '[')) ? json_decode($value, true) : $value, $fields);
                if ($this->eventCopyMismatch) {
                    $stored['promoted_object']['custom_event_type'] = 'PURCHASE';
                }
                $this->meta['adsets'][] = ['id' => '2002', ...$stored];
                if ($this->originalChangesDuringCopy) {
                    $this->meta['adsets'][0]['promoted_object']['custom_event_type'] = 'LEAD';
                }

                return Http::response(['id' => '2002']);
            }

            if ($request->method() === 'POST' && str_ends_with($path, '/budget_schedules')) {
                $fields = array_diff_key($request->data(), ['access_token' => true]);
                $this->meta['adsets'][1]['budget_schedules'] = ['data' => [['id' => '8001', ...$fields]]];
                $this->meta['adsets'][1]['is_budget_schedule_enabled'] = true;

                return Http::response(['id' => '8001']);
            }

            if ($request->method() === 'POST') {
                return Http::response(['success' => true]);
            }

            $owner = basename(dirname($path));

            return match (true) {
                str_ends_with($path, '/insights') => Http::response(['data' => [$this->delivered]]),
                str_ends_with($path, '/adsets') => Http::response(['data' => $this->adSetsOf($owner)]),
                str_ends_with($path, '/ads') => Http::response(['data' => $this->adsOf($owner)]),
                basename($path) === self::COPY_ID && $this->copiedCampaign !== null => Http::response($this->copiedCampaign),
                basename($path) === '2001' => Http::response($this->meta['adsets'][0]),
                default => Http::response($this->meta['campaign']),
            };
        });
    }

    /**
     * @param  array<string, mixed>  $fields
     * @return array<string, string>
     */
    private function copy(string $id, array $fields): array
    {
        $this->copies[] = ['id' => $id, 'fields' => $fields];

        if ($id === self::CAMPAIGN_ID) {
            $this->copiedCampaign = [...$this->meta['campaign'], 'id' => self::COPY_ID, 'name' => 'Winter Sale - copy', 'status' => $fields['status_option'], 'effective_status' => $fields['status_option']];

            return ['copied_campaign_id' => self::COPY_ID];
        }

        if ($id === '2001') {
            if ($this->adSetCopyFails) {
                return ['error' => ['message' => 'Invalid parameter', 'code' => 100]];
            }

            $adSetId = $fields['campaign_id'] === self::COPY_ID ? '2101' : '2002';
            $this->meta['adsets'][] = ['id' => $adSetId, 'name' => 'US mobile - copy', 'status' => $fields['status_option'], 'campaign_id' => $fields['campaign_id']];

            if ($fields['deep_copy'] === 'true') {
                $this->meta['ads'][] = ['id' => $adSetId === '2101' ? '3101' : '3002', 'name' => 'Video A - copy', 'status' => $fields['status_option'], 'adset_id' => $adSetId];
            }

            return ['copied_adset_id' => $adSetId];
        }

        $this->meta['ads'][] = ['id' => '3003', 'name' => 'Video A - copy', 'status' => $fields['status_option'], 'adset_id' => $fields['adset_id']];

        return ['copied_ad_id' => '3003'];
    }

    /** @return list<array<string, mixed>> */
    private function adSetsOf(string $campaignId): array
    {
        return array_values(array_filter($this->meta['adsets'], fn (array $row): bool => $row['campaign_id'] === $campaignId));
    }

    /** @return list<array<string, mixed>> */
    private function adsOf(string $parentId): array
    {
        $adSets = array_column($this->adSetsOf($parentId), 'id');

        return array_values(array_filter($this->meta['ads'], fn (array $row): bool => $row['adset_id'] === $parentId || in_array($row['adset_id'], $adSets, true)));
    }

    private function remove(string $id): bool
    {
        $this->deleted[] = $id;

        if ($id === self::COPY_ID) {
            $this->copiedCampaign = null;
        }

        foreach (['adsets', 'ads'] as $level) {
            $this->meta[$level] = array_values(array_filter($this->meta[$level], fn (array $row): bool => $row['id'] !== $id));
        }

        return true;
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'ad_account_id' => 'act_111',
            'currency' => 'USD',
            'external_campaign_id' => self::CAMPAIGN_ID,
            ...$attributes,
        ]);

        app(CampaignSynchronizer::class)->sync($campaign);

        return $campaign;
    }

    private function entity(Campaign $campaign, string $externalId): CampaignPlatformEntity
    {
        return $campaign->platformEntities()->where('external_id', $externalId)->sole();
    }

    private function editor(): EntityEditor
    {
        return app(EntityEditor::class);
    }

    private function capabilities(): EditCapabilities
    {
        return app(EditCapabilities::class);
    }

    // ------------------------------------------------------------- Duplicate

    private function eventCopySource(): Campaign
    {
        config(['campaign-manager.edit_categories' => ['name', 'optimization', 'duplicate', 'delete']]);
        $this->meta['adsets'][0] = [
            ...$this->meta['adsets'][0], 'account_id' => '111',
            'optimization_goal' => 'OFFSITE_CONVERSIONS', 'billing_event' => 'IMPRESSIONS',
            'promoted_object' => ['pixel_id' => '555', 'custom_event_type' => 'PURCHASE'],
            'daily_budget' => '700', 'lifetime_budget' => '0',
            'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
            'targeting' => ['geo_locations' => ['countries' => ['US']], 'device_platforms' => ['mobile']],
            'pacing_type' => ['standard'], 'destination_type' => 'WEBSITE',
            'attribution_spec' => [['event_type' => 'CLICK_THROUGH', 'window_days' => 7]],
            'is_dynamic_creative' => false, 'is_budget_schedule_enabled' => false,
        ];

        return $this->campaign();
    }

    public function test_event_copy_creates_with_the_new_event_and_paused_ads_without_editing_the_original(): void
    {
        $campaign = $this->eventCopySource();
        $entity = $this->entity($campaign, '2001');
        $baseline = $entity->editBaseline();
        $edit = $this->editor()->proposeAction($campaign, $entity, $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('ADD_TO_CART', $edit->details['conversion_event']);
        $this->assertSame(['status' => 'PAUSED', 'conversion_event' => 'ADD_TO_CART'], $edit->readback);
        $this->assertSame($baseline, $entity->refresh()->editBaseline());
        $this->assertSame('PAUSED', $this->entity($campaign, '3003')->status);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'POST'
            && str_ends_with($request->url(), '/act_111/adsets')
            && json_decode($request['promoted_object'], true) === ['pixel_id' => '555', 'custom_event_type' => 'ADD_TO_CART']
            && json_decode($request['targeting'], true) === $this->meta['adsets'][0]['targeting']
            && json_decode($request['attribution_spec'], true) === $this->meta['adsets'][0]['attribution_spec']
            && $request['daily_budget'] === '700' && ! isset($request['lifetime_budget'])
            && $request['status'] === 'PAUSED');
        Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST' && str_ends_with($request->url(), '/2001'));
    }

    public function test_event_copy_requires_acknowledgement_and_displays_the_exact_event_in_review(): void
    {
        $campaign = $this->eventCopySource();
        $wizard = Livewire::actingAs($this->user)->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, '2001')])
            ->set('copyConversionEvent', 'ADD_TO_CART')->call('reviewEventCopy')
            ->assertSee('Original event (unchanged)')->assertSee('ADD_TO_CART')
            ->assertSee('new learning')->call('confirm')
            ->assertSee('needs to be acknowledged');
        Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
        $wizard->set('acknowledged', true)->call('confirm')->assertSee('Done.');
        $this->assertSame('PURCHASE', $this->entity($campaign, '2001')->settings['promoted_object']['custom_event_type']);
    }

    public function test_event_copy_preserves_lifetime_budget_bidding_and_dayparting(): void
    {
        $campaign = $this->eventCopySource();
        $schedule = [['days' => [1, 2], 'start_minute' => 540, 'end_minute' => 1020, 'timezone_type' => 'ADVERTISER']];
        $end = now()->addDays(7)->toIso8601String();
        $this->meta['adsets'][0] = [
            ...$this->meta['adsets'][0], 'daily_budget' => '0', 'lifetime_budget' => '5000',
            'bid_strategy' => 'LOWEST_COST_WITH_BID_CAP', 'bid_amount' => '200',
            'pacing_type' => ['day_parting', 'no_pacing'], 'adset_schedule' => $schedule, 'end_time' => $end,
        ];
        app(CampaignSynchronizer::class)->sync($campaign);
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $this->assertSame(CampaignEntityEdit::Applied, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'POST'
            && str_ends_with($request->url(), '/act_111/adsets')
            && ! isset($request['daily_budget']) && $request['lifetime_budget'] === '5000'
            && $request['bid_strategy'] === 'LOWEST_COST_WITH_BID_CAP' && $request['bid_amount'] === '200'
            && json_decode($request['adset_schedule'], true) === $schedule
            && json_decode($request['pacing_type'], true) === ['day_parting', 'no_pacing']
            && $request['end_time'] === $end);
    }

    public function test_invalid_or_same_events_and_unknown_copy_details_are_refused(): void
    {
        $campaign = $this->eventCopySource();
        foreach ([
            ['conversion_event' => 'FAKE_EVENT'], ['conversion_event' => 'PURCHASE'],
            ['conversion_event' => ['ADD_TO_CART']], ['conversion_event' => 'ADD_TO_CART', 'status' => 'ACTIVE'],
        ] as $details) {
            try {
                $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, $details);
                $this->fail('Accepted invalid event-copy details.');
            } catch (EditRefused) {
                Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
            }
        }
    }

    public function test_event_copy_refuses_missing_pixel_wrong_entity_and_disabled_controls(): void
    {
        $campaign = $this->eventCopySource();
        $entity = $this->entity($campaign, '2001');
        $settings = $entity->settings;
        unset($settings['promoted_object']['pixel_id']);
        $entity->settings = $settings;
        $this->assertStringContainsString('pixel', $this->capabilities()->eventCopyRefusal($entity));
        $this->assertNotNull($this->capabilities()->eventCopyRefusal($this->entity($campaign, '3001')));
        config(['campaign-manager.edit_categories' => ['duplicate']]);
        $this->assertStringContainsString('not switched on', $this->capabilities()->eventCopyRefusal($entity));
        $this->expectException(EditRefused::class);
        $this->editor()->proposeAction($campaign, $entity, $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
    }

    public function test_event_copy_revalidates_controls_and_source_drift_before_writing(): void
    {
        $campaign = $this->eventCopySource();
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        config(['campaign-manager.edit_categories' => ['duplicate']]);
        try {
            $this->editor()->apply($edit, $this->user, acknowledged: true);
            $this->fail('Applied with conversion controls disabled.');
        } catch (EditRefused) {
            Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
        }
        config(['campaign-manager.edit_categories' => ['optimization', 'duplicate']]);
        $this->meta['adsets'][0]['targeting']['device_platforms'] = ['desktop'];
        $this->assertSame(CampaignEntityEdit::Stale, $this->editor()->apply($edit->fresh(), $this->user, acknowledged: true)->state);
        Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
    }

    public function test_event_copy_rolls_back_after_an_ad_copy_failure(): void
    {
        $campaign = $this->eventCopySource();
        $this->adCopyFails = true;
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Ad copy refused', $edit->error);
        $this->assertContains('2002', $this->deleted);
        $this->assertNotContains('2001', $this->deleted);
        $this->assertSame('PURCHASE', $this->entity($campaign, '2001')->settings['promoted_object']['custom_event_type']);
    }

    public function test_event_copy_with_a_different_readback_event_is_unconfirmed(): void
    {
        $campaign = $this->eventCopySource();
        $this->eventCopyMismatch = true;
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $this->assertSame(CampaignEntityEdit::Unconfirmed, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
    }

    public function test_event_copy_recreates_boosts_without_reusing_the_original_schedule_ids(): void
    {
        $campaign = $this->eventCopySource();
        $schedule = [
            'budget_value' => 1000, 'budget_value_type' => 'ABSOLUTE',
            'time_start' => now()->startOfHour()->addDays(2)->getTimestamp(),
            'time_end' => now()->startOfHour()->addDays(3)->getTimestamp(),
        ];
        $this->meta['adsets'][0]['budget_schedules'] = ['data' => [['id' => '7001', ...$schedule]]];
        $this->meta['adsets'][0]['is_budget_schedule_enabled'] = true;
        app(CampaignSynchronizer::class)->sync($campaign);
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('7001', $this->entity($campaign, '2001')->settings['budget_schedules'][0]['id']);
        $this->assertSame('8001', $this->entity($campaign, '2002')->settings['budget_schedules'][0]['id']);
        Http::assertSent(fn (Request $request): bool => $request->method() === 'POST'
            && str_ends_with($request->url(), '/2002/budget_schedules')
            && ! isset($request['id']) && (int) $request['budget_value'] === 1000);
    }

    public function test_failed_event_copy_reports_incomplete_cleanup_with_the_copy_id(): void
    {
        $campaign = $this->eventCopySource();
        $this->adCopyFails = true;
        $this->cleanupRefused = true;
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('cleanup of paused copy 2002 also failed', $edit->error);
        $this->assertNotContains('2001', $this->deleted);
    }

    public function test_event_copy_checks_native_ownership_before_creation(): void
    {
        $campaign = $this->eventCopySource();
        $this->meta['adsets'][0]['account_id'] = '999';
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('outside the requested campaign or account', $edit->error);
        Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
    }

    public function test_event_copy_does_not_claim_success_if_the_original_changes_during_copy(): void
    {
        $campaign = $this->eventCopySource();
        $this->originalChangesDuringCopy = true;
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $this->assertSame(CampaignEntityEdit::Unconfirmed, $this->editor()->apply($edit, $this->user, acknowledged: true)->state);
    }

    public function test_event_copy_does_not_silently_drop_an_expired_end_date(): void
    {
        $campaign = $this->eventCopySource();
        $this->meta['adsets'][0]['end_time'] = now()->subDay()->toIso8601String();
        app(CampaignSynchronizer::class)->sync($campaign);
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate, ['conversion_event' => 'ADD_TO_CART']);
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('original run has ended', $edit->error);
        Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST');
    }

    public function test_a_meta_ad_set_is_copied_paused_into_its_campaign(): void
    {
        $campaign = $this->campaign();
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate);

        $this->assertSame([], $this->capabilities()->actionConfirmations($edit->entity, CampaignEntityEdit::Duplicate, []));

        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('2001', $this->copies[0]['id']);
        $this->assertSame('PAUSED', $this->copies[0]['fields']['status_option']);
        $this->assertSame(self::CAMPAIGN_ID, $this->copies[0]['fields']['campaign_id']);

        $copy = $this->entity($campaign, '2002');
        $this->assertSame('PAUSED', $copy->status);
        $this->assertSame($copy->id, $edit->details['copy_entity_id']);
        $this->assertSame('Paused copy US mobile - copy', $edit->summary());
        $this->assertSame('ACTIVE', $this->entity($campaign, '2001')->status, 'The original is left as it was.');
    }

    public function test_a_meta_ad_set_with_several_ads_is_copied_bare_then_ad_by_ad(): void
    {
        $this->meta['ads'][] = ['id' => '3004', 'name' => 'Video B', 'status' => 'ACTIVE', 'adset_id' => '2001'];
        $campaign = $this->campaign();
        $edit = $this->editor()->apply($this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('false', $this->copies[0]['fields']['deep_copy']);
        $this->assertSame([['3001', '2002'], ['3004', '2002']], array_map(fn (array $copy): array => [$copy['id'], $copy['fields']['adset_id']], array_slice($this->copies, 1)));
    }

    public function test_a_meta_ad_is_copied_paused_into_its_ad_set(): void
    {
        $campaign = $this->campaign();
        $edit = $this->editor()->apply($this->editor()->proposeAction($campaign, $this->entity($campaign, '3001'), $this->user, CampaignEntityEdit::Duplicate), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['adset_id' => '2001', 'status_option' => 'PAUSED'], array_intersect_key($this->copies[0]['fields'], ['adset_id' => 1, 'status_option' => 1]));
        $this->assertSame('PAUSED', $this->entity($campaign, '3003')->status);
    }

    public function test_the_wizard_makes_the_copy_from_more_actions(): void
    {
        $campaign = $this->campaign();

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, '2001')])
            ->assertSee('More actions')
            ->call('propose', CampaignEntityEdit::Duplicate)
            ->assertSee('The copy is created paused')
            ->assertSee('Make the copy')
            ->call('confirm')
            ->assertSee('Edit the copy');

        $this->assertSame('PAUSED', $this->copies[0]['fields']['status_option']);
    }

    public function test_a_whole_meta_campaign_is_copied_paused_and_brought_into_the_manager(): void
    {
        $campaign = $this->campaign();
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, self::CAMPAIGN_ID), $this->user, CampaignEntityEdit::Duplicate);

        $this->assertStringContainsString('copies of its 1 ad set and their ads', (string) $this->capabilities()->actionSummary($edit->entity, CampaignEntityEdit::Duplicate));

        $edit = $this->editor()->apply($edit, $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['deep_copy' => 'false', 'status_option' => 'PAUSED'], array_intersect_key($this->copies[0]['fields'], ['deep_copy' => 1, 'status_option' => 1]));
        $this->assertSame(['id' => '2001', 'campaign_id' => self::COPY_ID, 'deep_copy' => 'true', 'status_option' => 'PAUSED'],
            ['id' => $this->copies[1]['id'], ...array_intersect_key($this->copies[1]['fields'], ['campaign_id' => 1, 'deep_copy' => 1, 'status_option' => 1])]);

        $copy = Campaign::findOrFail($edit->details['copy_campaign_id']);
        $this->assertSame([self::COPY_ID, $this->user->id, 'published'], [$copy->external_campaign_id, $copy->user_id, $copy->status]);
        $this->assertSame(['2101', '3101'], $copy->platformEntities()->whereIn('entity_type', ['ad_set', 'ad'])->orderBy('external_id')->pluck('external_id')->all());
        $this->assertSame(['2001', '3001'], $campaign->platformEntities()->whereIn('entity_type', ['ad_set', 'ad'])->orderBy('external_id')->pluck('external_id')->all(), 'The original keeps only its own children.');
    }

    public function test_an_ad_set_with_more_ads_than_one_call_copies_is_copied_bare_then_ad_by_ad(): void
    {
        foreach (['3004', '3005', '3006'] as $id) {
            $this->meta['ads'][] = ['id' => $id, 'name' => 'Video '.$id, 'status' => 'ACTIVE', 'adset_id' => '2001'];
        }

        $campaign = $this->campaign();
        $edit = $this->editor()->apply($this->editor()->proposeAction($campaign, $this->entity($campaign, self::CAMPAIGN_ID), $this->user, CampaignEntityEdit::Duplicate), $this->user);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('false', $this->copies[1]['fields']['deep_copy']);
        $this->assertSame(['3001', '3004', '3005', '3006'], array_column(array_slice($this->copies, 2), 'id'));
        $this->assertSame(['2101'], array_unique(array_column(array_column(array_slice($this->copies, 2), 'fields'), 'adset_id')));
    }

    public function test_a_campaign_copy_that_fails_part_way_is_deleted_again(): void
    {
        $this->adSetCopyFails = true;
        $campaign = $this->campaign();
        $edit = $this->editor()->apply($this->editor()->proposeAction($campaign, $this->entity($campaign, self::CAMPAIGN_ID), $this->user, CampaignEntityEdit::Duplicate), $this->user);

        $this->assertNotSame(CampaignEntityEdit::Applied, $edit->state);
        $this->assertContains(self::COPY_ID, $this->deleted);
        $this->assertFalse(Campaign::where('external_campaign_id', self::COPY_ID)->exists());
    }

    public function test_the_wizard_links_to_the_copied_campaign(): void
    {
        $campaign = $this->campaign();

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, self::CAMPAIGN_ID)])
            ->call('propose', CampaignEntityEdit::Duplicate)
            ->assertSee('copy of this whole campaign')
            ->set('acknowledged', true)
            ->call('confirm')
            ->assertSee('Open the copy');
    }

    public function test_what_cannot_be_copied_says_why(): void
    {
        $campaign = $this->campaign();

        $this->assertNull($this->capabilities()->actionRefusal($this->entity($campaign, self::CAMPAIGN_ID), CampaignEntityEdit::Duplicate));

        config(['campaign-manager.edit_categories' => ['name']]);
        $this->assertSame('Duplicating is not switched on for the campaign manager.', $this->capabilities()->actionRefusal($this->entity($campaign, '2001'), CampaignEntityEdit::Duplicate));

        $this->expectException(EditRefused::class);
        $this->editor()->proposeAction($campaign, $this->entity($campaign, '2001'), $this->user, CampaignEntityEdit::Duplicate);
    }

    // ---------------------------------------------------------------- Delete

    public function test_a_delivered_ad_is_deleted_only_once_acknowledged(): void
    {
        $this->delivered = ['spend' => '42.50', 'impressions' => '12000'];
        $campaign = $this->campaign();
        $ad = $this->entity($campaign, '3001');
        $edit = $this->editor()->proposeAction($campaign, $ad, $this->user, CampaignEntityEdit::Delete);

        $notes = implode(' ', $this->capabilities()->actionConfirmations($ad, CampaignEntityEdit::Delete, $edit->details));
        $this->assertStringContainsString('cannot be undone', $notes);
        $this->assertStringContainsString('42.50 USD spent and 12,000 impressions', $notes);
        $this->assertStringContainsString('is on, so anything it is delivering now stops', $notes);

        try {
            $this->editor()->apply($edit, $this->user);
            $this->fail('A delete went out without being acknowledged.');
        } catch (EditRefused $refused) {
            $this->assertStringContainsString('needs to be acknowledged', $refused->getMessage());
        }

        $this->assertSame([], $this->deleted);

        $edit = $this->editor()->apply($edit->refresh(), $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['3001'], $this->deleted);
        $this->assertNotNull($ad->fresh()->removed_at);
        $this->assertSame('Delete', $edit->summary());
    }

    public function test_a_delete_is_not_sent_when_the_object_delivered_since_it_was_proposed(): void
    {
        $this->delivered = ['spend' => '10', 'impressions' => '500'];
        $campaign = $this->campaign();
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, '3001'), $this->user, CampaignEntityEdit::Delete);

        $this->delivered = ['spend' => '11', 'impressions' => '540'];
        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        $this->assertStringContainsString('has delivered since the delete was proposed', (string) $edit->error);
        $this->assertSame([], $this->deleted);
    }

    public function test_deleting_the_campaign_removes_its_children_first_and_returns_it_to_draft(): void
    {
        $campaign = $this->campaign(['activated_at' => now()]);
        $edit = $this->editor()->proposeAction($campaign, $this->entity($campaign, self::CAMPAIGN_ID), $this->user, CampaignEntityEdit::Delete);

        $this->assertStringContainsString('leaves the campaign manager', implode(' ', $this->capabilities()->actionConfirmations($edit->entity, CampaignEntityEdit::Delete, $edit->details)));

        $edit = $this->editor()->apply($edit, $this->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['3001', '2001', self::CAMPAIGN_ID], $this->deleted);
        $this->assertSame(['deleted' => true], $edit->readback);

        $campaign->refresh();
        $this->assertNull($campaign->external_campaign_id);
        $this->assertNull($campaign->activated_at);
        $this->assertSame(0, $campaign->platformEntities()->whereNull('removed_at')->count());
    }

    public function test_the_wizard_returns_to_the_list_after_the_campaign_is_deleted(): void
    {
        $campaign = $this->campaign();

        Livewire::actingAs($this->user)
            ->test(EditEntity::class, ['campaign' => $campaign, 'entity' => $this->entity($campaign, self::CAMPAIGN_ID)])
            ->call('propose', CampaignEntityEdit::Delete)
            ->assertSee('Delete permanently')
            ->set('acknowledged', true)
            ->call('confirm')
            ->assertRedirect(route('campaign-manager.index'))
            ->assertSessionHas('campaign-manager.status');
    }

    // -------------------------------------------------------------- LinkedIn

    public function test_linkedin_allows_copies_but_refuses_deleting_non_empty_parents(): void
    {
        $linkedin = Mockery::mock(LinkedIn::class);
        $linkedin->shouldReceive('campaignConversions')->andReturn([]);
        $linkedin->shouldReceive('on')->andReturnSelf();
        $linkedin->shouldReceive('campaign')->andReturn(['id' => 555, 'name' => 'Lead gen', 'status' => 'ACTIVE', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:44']);
        $linkedin->shouldReceive('campaignGroup')->andReturn(['id' => 44, 'name' => 'Q4', 'status' => 'ACTIVE']);
        $linkedin->shouldReceive('creatives')->andReturn(['elements' => [['id' => 'urn:li:sponsoredCreative:77', 'intendedStatus' => 'ACTIVE', 'campaign' => 'urn:li:sponsoredCampaign:555', 'content' => ['reference' => 'urn:li:share:88']]], 'next_page_token' => null]);
        $linkedin->shouldReceive('campaigns')->andReturn(['elements' => [], 'next_page_token' => null]);
        $this->app->instance(LinkedIn::class, $linkedin);

        $campaign = $this->campaign(['platform' => 'linkedin', 'ad_account_id' => 'urn:li:sponsoredAccount:999', 'external_campaign_id' => '555']);
        $linkedInCampaign = $this->entity($campaign, '555');

        $this->assertNull($this->capabilities()->actionRefusal($linkedInCampaign, CampaignEntityEdit::Duplicate));
        $this->assertSame('This campaign still holds 1 ad. LinkedIn only deletes an empty one, so delete those first.', $this->capabilities()->actionRefusal($linkedInCampaign, CampaignEntityEdit::Delete));
        $creativeActions = $this->capabilities()->actions($this->entity($campaign, '77'));
        $this->assertNull($creativeActions[CampaignEntityEdit::Duplicate]);
        $this->assertNull($creativeActions[CampaignEntityEdit::Delete], 'An ad has no children, so it can be deleted.');
    }
}
